package com.zdc.encrypt;

import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.util.*;

/**
 * @author zdc
 * @description
 * @date 2025/8/14 10:39
 */
public class InMemoryYamlLoader implements PropertySourceLoader {

    private static final Map<String, Map<String, Object>> YAML_CACHE = new HashMap<>();

    public static void addYamlToCache(String name, String yamlContent) {
        Yaml yaml = new Yaml();
        Map<String, Object> loaded = yaml.load(yamlContent);
        YAML_CACHE.put(name, flattenMap(loaded));
    }

    @Override
    public String[] getFileExtensions() {
        return new String[]{"yml", "yaml"};
    }

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        System.out.println("Loading configuration for: " + name);
        if (YAML_CACHE.containsKey(name)) {
            return Collections.singletonList(new MapPropertySource(name, YAML_CACHE.get(name))
            );
        }
        return Collections.emptyList();
    }

    private static Map<String, Object> flattenMap(Map<String, Object> source) {
        Map<String, Object> result = new LinkedHashMap<>();
        flattenMap("", source, result);
        return result;
    }

    private static void flattenMap(String prefix, Map<String, Object> source,
                                   Map<String, Object> result) {
        source.forEach((key, value) -> {
            String fullKey = prefix.isEmpty() ? key : prefix + "." + key;
            if (value instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> nestedMap = (Map<String, Object>) value;
                flattenMap(fullKey, nestedMap, result);
            } else {
                result.put(fullKey, value);
            }
        });
    }
}